# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils import simplejson
from django.utils.translation import ugettext_noop as _n

from datetime import datetime
from requests.constants import PENDING_REQUEST, REJECTED_REQUEST, APPROVED_REQUEST, EDIT_REQUEST, REMOVE_REQUEST
from requests import apply_changes


class Request(models.Model):
    class Meta:
        permissions = (
            (u'can_moderate', _n(u'Can moderate requests')),
        )
    type = models.SmallIntegerField(editable=False)
    status = models.SmallIntegerField(default=PENDING_REQUEST, editable=False)
    date_open = models.DateTimeField(default=datetime.now, editable=False)
    date_close = models.DateTimeField(null=True, editable=False)
    user = models.ForeignKey(User, related_name='requests_opened', editable=False)
    moderator = models.ForeignKey(User, related_name='requests_closed', null=True, editable=False)
    user_comment = models.TextField(blank=True)
    mod_comment = models.TextField(blank=True)
    data = models.TextField(default='', blank=True)
    content_type = models.ForeignKey(ContentType, editable=False)
    object_id = models.PositiveIntegerField(editable=False)
    content_object = GenericForeignKey()
    
    def accept(self, mod, comment):
        obj = self.content_object
        if self.type == REMOVE_REQUEST:
            obj.auth = REJECTED_REQUEST
        else:
            obj.auth = APPROVED_REQUEST
            if self.type == EDIT_REQUEST:
                apply_changes(obj, self.data)
        obj.save()
        self.status = APPROVED_REQUEST
        self.date_close = datetime.now()
        self.moderator = mod
        self.mod_comment = comment
        self.save()
        if hasattr(obj, 'accept_callback'):
            obj.accept_callback(self.data)
    
    def reject(self, mod, comment):
        self.status = REJECTED_REQUEST
        self.moderator = mod
        self.mod_comment = comment
        self.save()
        if hasattr(self.content_object, 'reject_callback'):
            self.content_object.reject_callback()
